import type { Module } from "vuex";
import { LoginState } from "./types";
import { RooTState } from "../types";
import User from "@/service/api/user/user";
import { localCache } from "@/utils";
import router from "@/router";

const loginModule: Module<LoginState, RooTState> = {
  namespaced: true,
  state(): any {
    return {
      token: "",
      userInfo: {},
      userMenuList: [],
    };
  },

  mutations: {
    changeToken(state, token: string) {
      state.token = token;
      console.log("token设置完成", state.userInfo, state.userMenuList);
    },
    changeUserInfo(state, payload: any) {
      state.userInfo = payload;
    },
    changeMenuList(state, payload = []) {
      state.userMenuList = payload;
    },
  },
  getters: {},
  actions: {
    async accountLoginAction({ commit }, payload: any) {
      const loginRes = await User.accountLoginRequest(payload);
      if (loginRes.code === "200") {
        const { token } = loginRes.data;
        commit("changeToken", token);
        localCache.setCache("token", token);
      }

      //2.请求用户信息
      const userInfoResult = await User.requsetUserInfoById();
      if (userInfoResult.code === "200") {
        commit("changeUserInfo", userInfoResult.data);
      }

      //3.获取用户菜单
      const userMenuResult = await User.requsetUserMenuById();
      if (userMenuResult.code === "200") {
        commit("changeMenuList", userMenuResult.data);
      }

      router.push("/");
    },

    phoneLoaginAction({ commit }, payload: any) {
      console.log("执行手机actions", payload);
    },
  },
};

export default loginModule;
